<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
/* 
	模拟http请求类
*/
class Http{
	
	public function __construct(){}
	
	public function request($url, $params = array(), $method = 'GET', $header = null){
		if(!function_exists('curl_init')){
			return '';
		}
		$method = strtoupper($method);
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		if($header){
			curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		}
		
		// ssl
		if(isset($params['ssl_cert']) && isset($params['ssl_key'])){
			curl_setopt($curl, CURLOPT_SSLCERT, $params['ssl_cert']);
			curl_setopt($curl, CURLOPT_SSLKEY, $params['ssl_key']);
			unset($params['ssl_cert'], $params['ssl_key']);
			$params = $params['data'];
		}
		
		// 上传
		if(isset($params['curl_upload']) && $params['curl_upload'] === 1){
			if(class_exists('\CURLFile')){
				curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
				foreach($params as &$val){
					if(substr($val, 0, 1) == '@'){
						$val = new \CURLFile(ltrim($val, '@'));
						$fileinfo = pathinfo($val->getFilename());
						$val->setPostFilename($fileinfo['basename']);
					}
				}
			}else{
				if (defined('CURLOPT_SAFE_UPLOAD')) {
					curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
				}
			}
			unset($params['curl_upload']);
		}
		
		switch($method){
			case 'GET':
				if($params){
                    $url = $url.(strpos($url, '?') ? '&' : '?').(is_array($params) ? http_build_query($params) : $params);
                }
				break;
			case 'POST':
				curl_setopt($curl, CURLOPT_POST, 1);
				if($params){
					curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
				}
				break;
		}
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		curl_setopt($curl, CURLOPT_MAXREDIRS, 4);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
	}
	
}